package com.uniapp.server.controller;

import com.uniapp.server.common.R;
import com.uniapp.server.config.jwt.JwtConfig;
import com.uniapp.server.model.UserEntity;
import com.uniapp.server.security.JwtAuthenticationFilter;
import com.uniapp.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cyt
 * @describe
 * @create 2021-01-18 17:38
 */
@CrossOrigin
@RequestMapping("/api")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    JwtAuthenticationFilter jwtAuthenticationFilter;

    @PostMapping("/login")
    public R login(@RequestBody UserEntity userEntity) {
        boolean login = userService.login(userEntity.getUsername());
        if (login) {
            String token = jwtConfig.generateToken(userEntity.getUsername());
            return R.ok().data("token", token).data("username", userEntity.getUsername());
        } else {
            return R.error();
        }
    }

    @GetMapping("/getInfo")
    public R getInfo(HttpServletRequest request, HttpServletResponse response) {
        String jwt = jwtAuthenticationFilter.getJwtTokenFromRequest(request, response);
        UserEntity userInfo = userService.getUserInfo(jwtConfig.getUserInfoFromToken(jwt));
        return R.ok().data("user", userInfo);
    }
}
